<?php

namespace backend\modules\member\controllers;

use Yii;
use yii\web\UnprocessableEntityHttpException;
use common\traits\MerchantCurd;
use common\enums\StatusEnum;
use addons\Member\common\models\Member;
use common\queues\MailerJob;
use common\models\base\SearchModel;
use backend\controllers\BaseController;
use common\models\member\MassRecord;
use common\enums\MassRecordSendTypeEnum;

/**
 * 群发消息控制器
 *
 * Class MassRecordController
 * @package addons\Wechat\merchant\controllers
 * @author YiiFrame <21931118@qq.com>
 */
class MassRecordController extends BaseController
{
    use MerchantCurd;

    /**
     * @var MassRecord
     */
    public $modelClass = MassRecord::class;

    /**
     * 首页
     *
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionEmail()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'partialMatchAttributes' => [], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query
            ->andWhere(['>=', 'status', StatusEnum::DISABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()]);

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    /**
     * 编辑/创建
     *
     * @return mixed|string|\yii\web\Response
     * @throws UnprocessableEntityHttpException
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \yii\base\ExitException
     */
    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', null);
        $model = $this->findModel($id);
        $this->activeFormValidate($model);
        if ($model->load($request->post())) {
            try {
                $messageIds = [];
                if (!$model->save()) {
                    throw new UnprocessableEntityHttpException($this->getError($model));
                }

                switch ($model->send_type) {
                    case MassRecordSendTypeEnum::AT_ONCE:
                    case MassRecordSendTypeEnum::TIMING:
//                        $delay = $model->send_time - time();
//                        $delay < 0 && $delay = 0;
//                        $model->send_type == MassRecordSendTypeEnum::AT_ONCE && $delay = 0;
//                        if ($model->tag_id > 0) {
//                            $members = Yii::$app->services->memberTagMap->getMemberByTagId($model->tag_id);
//                        } else {
//                            $members = Member::find()
//                                ->select(['id', 'nickname', 'mobile', 'email', 'head_portrait'])
//                                ->where(['status' => StatusEnum::ENABLED])
//                                ->asArray()
//                                ->all();
//                        }
//
//                        foreach ($members as $item) {
//                            if (!empty($item['email'])) {
//                                $messageIds[] = Yii::$app->queue->delay($delay)->push(new MailerJob([
//                                    'user' => $item,
//                                    'email' => $item['email'],
//                                    'subject' => $model->title,
//                                    'template' => 'memberMessage',
//                                    'data' => $model,
//                                ]));
//                            }
//                        }
//
//                        $model->member_num = count($messageIds);
//                        $model->message_ids = $messageIds;
                        break;
                    case MassRecordSendTypeEnum::TEST:
//                        $model->member_num = 1;
//                        $user = Yii::$app->services->member->findByEmail($model->test_account);
//                        Yii::$app->services->mailer->realSend($user, $model->test_account, $model->title, 'memberMessage', $model);
                        break;
                }

                if (!$model->save()) {
                    throw new UnprocessableEntityHttpException($this->getError($model));
                }

                return $this->redirect(['email']);
            } catch (\Exception $e) {
                return $this->message($e->getMessage(), $this->redirect(['email']), 'error');
            }
        }

        return $this->render($this->action->id, [
            'model' => $model,
            'tags' => Yii::$app->services->memberTag->getMap(),
        ]);
    }
}